package summarizer.newversion;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;

import metrics.JSDivergence;

import thesis.FSModule;
import thesis.InfoUnit;
import thesis.DataObject;
import thesis.Summary;
import thesis.DataUtil;

public class SampleSummarizer extends Summarizer {
	private final double alpha;
	private final double beta;
	private final double gamma;
	private final double[][] probs;
	private final ArrayList<InfoUnit> infoUnits;
	private HashMap<Long, DataObject> memoryTweets;

	public SampleSummarizer(double[][] probs, ArrayList<InfoUnit> infoUnits,
			double alpha, double beta, double gamma) {
		this.alpha = alpha;
		this.beta = beta;
		this.gamma = gamma;

		this.probs = probs;
		this.infoUnits = infoUnits;
	}

	private double[] getHistogram(ArrayList<DataObject> set) {
		double[] po = new double[this.infoUnits.size()];
		for (int i = 0; i < po.length; i++) {
			po[i] = 0;
		}
		double total = 0;
		for (DataObject t : set) {
			for (int i = 0; i < infoUnits.size(); i++) {
				po[i] += infoUnits.get(i).getWeight()
						* probs[t.getInternId()][infoUnits.get(i).getInternId()];
				total += infoUnits.get(i).getWeight()
						* probs[t.getInternId()][infoUnits.get(i).getInternId()];
			}
		}
		for (int i = 0; i < po.length; i++) {
			po[i] = (po[i] + JSDivergence.eps)
					/ (total + JSDivergence.eps * po.length);
		}
		return po;
	}

	public Summary computeSummary(int summaryDimension, int numberOfPages,
			HashMap<Long, DataObject> tweets, int dimSize) {
		int numIteration = 5000;
		this.memoryTweets = tweets;
		executionTime = (new GregorianCalendar()).getTimeInMillis();
		ArrayList<DataObject> allTweets = new ArrayList<DataObject>();
		for (DataObject t : tweets.values()) {
			allTweets.add(t);
		}
		double[] po = getHistogram(allTweets);
		Summary bestSummary = null;
		double bestS = -10000;
		for (int i = 0; i < numIteration; i++) {
			Summary summary = RandomSummarizer.randomSummary(summaryDimension,
					allTweets);
			double[] ps = getHistogram(summary.getMemoryTweets());
			double kl = JSDivergence.getKL(po, ps);
			if (bestS <= 1 - kl) {
				bestS = 1 - kl;
				bestSummary = summary;
			}
		}
		executionTime = (new GregorianCalendar()).getTimeInMillis()
				- executionTime;
		return bestSummary;
	}

	public String toString() {
		return "Sampling Summarizer <" + alpha + " " + beta + " " + gamma + ">";
	}

	public long getExecutionTime() {
		return executionTime;
	}
}
